package com.guashu.jaywayjsonpath.jasonPath;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jayway.jsonpath.DocumentContext;
import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.PathNotFoundException;
import net.minidev.json.JSONArray;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DynamicJsonPathExtractor {

    public static void main(String[] args) throws Exception {
        String json = JsonStr.getJsonString();
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode rootNode = objectMapper.readTree(json);

        Map<String, String> fieldJsonPaths = new HashMap<>();
        fieldJsonPaths.put("pa01bi01", "$.PRH.PA01.PA01B.PA01BI01");
        fieldJsonPaths.put("pd01ad01", "$.PDA.PD01[*].PD01A.PD01AD01");
        fieldJsonPaths.put("pd01bd01", "$.PDA.PD01[*].PD01B.PD01BD01");
        fieldJsonPaths.put("pd01ai01", "$.PDA.PD01[*].PD01A.PD01AI01");
        fieldJsonPaths.put("pd01er03", "$.PDA.PD01[*].PD01E.PD01EH[*].PD01ER03");
        fieldJsonPaths.put("pd01ed01", "$.PDA.PD01[*].PD01E.PD01EH[*].PD01ED01");
        fieldJsonPaths.put("pd01ej01", "$.PDA.PD01[*].PD01E.PD01EH[*].PD01EJ01");

        List<String> results = extractDataToList(rootNode, fieldJsonPaths);
        System.out.println("最终生成："+ JSON.toJSON(results));
    }

    private static List<String> extractDataToList(JsonNode rootNode, Map<String, String> fieldJsonPaths) throws Exception {
        List<String> results = new ArrayList<>();
        DocumentContext jsonContext = JsonPath.parse(rootNode.toString());

        // 动态遍历JSON Path
        fieldJsonPaths.forEach((key, jsonPath) -> {
            try {
                Object extractedData = jsonContext.read(jsonPath);
                if (extractedData instanceof JSONArray) {
                    // 如果提取的数据是数组
                    JSONArray dataArray = (JSONArray) extractedData;
                    dataArray.forEach(item -> {
                        // 处理数组中的每个元素
                        results.add(item.toString()); // 或者根据需要进行更复杂的处理
                    });
                } else {
                    // 如果提取的数据是单个值
                    results.add(extractedData.toString());
                }
            } catch (PathNotFoundException e) {
                // 如果路径不存在，添加null到结果列表
                results.add("null");
            }
        });

        return results;
    }
}
